package com.ruoyi.web.controller.wx_warehouseman;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserOnlineService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(value = "微信小程序仓管员登陆")
@RestController
@RequestMapping("/wx/warehouseman")
@Slf4j
public class warehouseLoginController {

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysUserService userService;


    /**
     * 仓管员登录方法
     *
     * @param loginBody 包含用户名及密码
     * @return 返回成功后生成的此用户token
     */
    @PostMapping("/login")
    public AjaxResult wxLoginCarrier(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.wxLogin(loginBody.getUsername(), loginBody.getPassword());
        redisCache.setCacheObject("App-Token-warehouseman", token, 30, TimeUnit.DAYS);     //token存redis,30天过期
        //查询仓管员ID
//        if (token != null){     //正常登陆
        SysUser user = userService.selectUserByUserName(loginBody.getUsername());
        //通过用户ID查询关联仓库ID
        List<Map<String, Object>> list = userService.getLocationByUserId(user.getUserId());
        //通过用户ID查询用户角色
        String role = userService.selectUserRoleGroup(user.getUserName());
        String adminRole = "";
        if (role.contains("仓管员")){
            adminRole = "仓管员";
        } else if (role.contains("物业")){
            adminRole = "物业";
        } else {
            return AjaxResult.error("用户未分配指定角色");
        }
        List<String> locationList = new LinkedList<>();
        if (list.size() > 0) {
            for (Map<String, Object> stringObjectMap : list) {
                locationList.add((String) stringObjectMap.get("name"));
            }
        } else {        //方便小程序判断
            locationList = null;
        }
        ajax.put("nickName",user.getNickName());
        ajax.put("userId",user.getUserId());
        ajax.put("avatar",user.getAvatar());        //暂时用来绑定仓库名称
        ajax.put("data", locationList);
        ajax.put("role", adminRole);
//        }
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}
